<template>
  <div class="shop-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>店铺管理</h2>
      <el-button type="primary" @click="showAddDialog"> 添加店铺 </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <SearchCard
      :default-values="{ search: '', platform: '', customerId: '' }"
      @search="handleSearch"
      @reset="handleReset"
    >
      <template #default="{ searchForm }">
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.search"
            placeholder="店铺名/店铺ID/客户姓名"
            clearable
            @keyup.enter="handleSearch"
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属平台">
          <el-select
            v-model="searchForm.platform"
            placeholder="全部平台"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="(config, key) in PLATFORMS"
              :key="key"
              :label="config.label"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="searchForm.customerId"
            placeholder="全部客户"
            clearable
            filterable
            style="width: 120px"
          >
            <el-option
              v-for="customer in customers"
              :key="customer._id"
              :label="customer.name"
              :value="customer._id"
            />
          </el-select>
        </el-form-item>
      </template>
    </SearchCard>

    <!-- 店铺列表 -->
    <DataTable
      title="店铺列表"
      :data="shops"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.limit"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="序号" width="60" align="center">
        <template #default="{ $index }">
          {{ (pagination.page - 1) * pagination.limit + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="shopName" label="店铺名" min-width="150" />
      <el-table-column prop="shopId" label="店铺ID" min-width="120" />
      <el-table-column prop="customerName" label="所属客户" min-width="100" />
      <el-table-column prop="platform" label="所属平台" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getPlatformTagType(row.platform)">
            {{ getPlatformLabel(row.platform) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="快递公司" min-width="250">
        <template #default="{ row }">
          <div class="express-companies">
            <div
              v-for="express in row.expressCompanies"
              :key="express"
              class="express-item"
            >
              <el-tag size="small" class="express-tag">
                {{ getExpressLabel(express) }}
              </el-tag>
              <el-tag
                :type="
                  getWaybillCountType(
                    row.expressStats?.[express]?.remaining || 0
                  )
                "
                size="small"
                class="count-tag"
              >
                {{ row.expressStats?.[express]?.remaining || 0 }}
              </el-tag>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        min-width="200"
        fixed="right"
        align="center"
      >
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="showDetailDialog(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 添加/编辑店铺对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="shopFormRef"
        :model="shopForm"
        :rules="shopRules"
        label-width="100px"
      >
        <el-form-item label="店铺名" prop="shopName">
          <el-input
            v-model="shopForm.shopName"
            placeholder="请输入店铺名"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="店铺ID" prop="shopId">
          <el-input
            v-model="shopForm.shopId"
            placeholder="请输入店铺ID"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="所属客户" prop="customerId">
          <el-select
            v-model="shopForm.customerId"
            placeholder="请选择客户"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="customer in customers"
              :key="customer._id"
              :label="customer.name"
              :value="customer._id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属平台" prop="platform">
          <el-select
            v-model="shopForm.platform"
            placeholder="请选择平台"
            style="width: 100%"
          >
            <el-option
              v-for="(config, key) in PLATFORMS"
              :key="key"
              :label="config.label"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="快递公司" prop="expressCompanies">
          <el-select
            v-model="shopForm.expressCompanies"
            multiple
            placeholder="请选择快递公司"
            style="width: 100%"
          >
            <el-option
              v-for="(label, key) in EXPRESS_COMPANIES"
              :key="key"
              :label="label"
              :value="key"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 店铺详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="店铺详情" width="600px">
      <el-descriptions :column="2" border v-if="currentShop">
        <el-descriptions-item label="店铺名">{{
          currentShop.shopName
        }}</el-descriptions-item>
        <el-descriptions-item label="店铺ID">{{
          currentShop.shopId
        }}</el-descriptions-item>
        <el-descriptions-item label="所属客户">{{
          currentShop.customerName
        }}</el-descriptions-item>
        <el-descriptions-item label="所属平台">
          <el-tag :type="getPlatformTagType(currentShop.platform)">
            {{ getPlatformLabel(currentShop.platform) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="快递公司" :span="2">
          <div class="express-companies">
            <div
              v-for="express in currentShop.expressCompanies"
              :key="express"
              class="express-item"
            >
              <el-tag class="express-tag">
                {{ getExpressLabel(express) }}
              </el-tag>
              <el-tag
                :type="
                  getWaybillCountType(
                    currentShop.expressStats?.[express]?.remaining || 0
                  )
                "
                class="count-tag"
              >
                剩余: {{ currentShop.expressStats?.[express]?.remaining || 0 }}
              </el-tag>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentShop.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import api from "@/utils/api";
import DataTable from "@/components/DataTable.vue";
import SearchCard from "@/components/SearchCard.vue";
import { getBatchShopWaybillStats } from "@/services/waybillService";
import { PLATFORMS, EXPRESS_COMPANIES } from "@/utils/constants";
import {
  getPlatformLabel,
  getPlatformTagType,
  getExpressLabel,
  formatDate,
} from "@/utils/helpers";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const shops = ref([]);
const customers = ref([]);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);
const currentShop = ref(null);
const shopFormRef = ref();

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 店铺表单
const shopForm = reactive({
  shopName: "",
  shopId: "",
  customerId: "",
  platform: "",
  expressCompanies: [],
});

// 表单验证规则
const shopRules = {
  shopName: [
    { required: true, message: "请输入店铺名", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "店铺名长度在 2 到 100 个字符",
      trigger: "blur",
    },
  ],
  shopId: [
    { required: true, message: "请输入店铺ID", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "店铺ID长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
  customerId: [
    { required: true, message: "请选择所属客户", trigger: "change" },
  ],
  platform: [{ required: true, message: "请选择所属平台", trigger: "change" }],
  expressCompanies: [
    { required: true, message: "请选择至少一个快递公司", trigger: "change" },
  ],
};

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑店铺" : "添加店铺"));

// 获取面单数量标签类型
const getWaybillCountType = (count) => {
  if (count === 0) return "danger";
  if (count < 10) return "warning";
  return "success";
};

// 获取客户列表
const fetchCustomers = async () => {
  try {
    const response = await api.get("/customers", { params: { limit: 1000 } });
    customers.value = response.data.customers;
  } catch (error) {
    ElMessage.error("获取客户列表失败");
  }
};

// 获取店铺列表
const fetchShops = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      search: searchForm?.search || "",
      platform: searchForm?.platform || "",
      customerId: searchForm?.customerId || "",
    };

    const response = await api.get("/shops", { params });
    shops.value = response.data.shops;
    pagination.total = response.data.total;

    // 批量获取店铺快递公司面单统计
    if (shops.value.length > 0) {
      const shopIds = shops.value.map((s) => s._id);
      const expressStats = await getBatchShopWaybillStats(shopIds);

      shops.value.forEach((shop) => {
        shop.expressStats = expressStats[shop._id] || {};
      });
    }
  } catch (error) {
    ElMessage.error("获取店铺列表失败");
  } finally {
    loading.value = false;
  }
};

let searchForm = null;

// 搜索
const handleSearch = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchShops();
};

// 重置搜索
const handleReset = (form) => {
  searchForm = form;
  pagination.page = 1;
  fetchShops();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchShops();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchShops();
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (shop) => {
  isEdit.value = true;
  currentShop.value = shop;
  Object.assign(shopForm, shop);
  dialogVisible.value = true;
};

// 显示详情对话框
const showDetailDialog = (shop) => {
  currentShop.value = shop;
  detailDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(shopForm, {
    shopName: "",
    shopId: "",
    customerId: "",
    platform: "",
    expressCompanies: [],
  });
  shopFormRef.value?.resetFields();
  shopFormRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!shopFormRef.value) return;

  try {
    const valid = await shopFormRef.value.validate();
    if (!valid) return;
  } catch {
    return;
  }

  submitLoading.value = true;

  try {
    if (isEdit.value) {
      await api.put(`/shops/${currentShop.value._id}`, shopForm);
      ElMessage.success("店铺更新成功");
    } else {
      await api.post("/shops", shopForm);
      ElMessage.success("店铺创建成功");
    }

    dialogVisible.value = false;
    fetchShops();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 删除店铺
const handleDelete = async (shop) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺 "${shop.shopName}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await api.delete(`/shops/${shop._id}`);
    ElMessage.success("店铺删除成功");
    fetchShops();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomers();
  fetchShops();
});
</script>

<style lang="scss" scoped>
.shop-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-primary;
      font-size: 20px;
      font-weight: 600;
    }
  }

  .express-companies {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .express-item {
      display: flex;
      align-items: center;
      gap: 4px;
      margin-bottom: 4px;

      .express-tag {
        font-size: 12px;
      }

      .count-tag {
        font-size: 11px;
        min-width: 40px;
        text-align: center;
      }
    }
  }

  .operation-buttons {
    display: flex;
    gap: 6px;
    white-space: nowrap;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .shop-management {
    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }

    .operation-buttons {
      flex-direction: column;
      gap: 4px;
    }

    .express-companies {
      .express-item {
        flex-direction: column;
        gap: 2px;
      }
    }
  }
}
</style>
